package com.itheima.health.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import com.itheima.health.mapper.OrderMapper;
import com.itheima.health.pojo.Member;
import com.itheima.health.pojo.Order;
import com.itheima.health.service.MemberService;
import com.itheima.health.service.OrderService;
import com.itheima.health.service.OrderSettingService;
import com.itheima.health.utils.date.DateUtils;
import com.itheima.health.utils.redis.RedisUtil;
import com.itheima.health.utils.resources.RedisMessageConstant;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;

/**
 *    预约   ：
 *      1.  验证码判断
 *      2.  是否预约满
 *      3.  重复预约
 *      4. 预约 成功更新多表
 */
@Service
@Transactional
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    //  服务和服务之间调用     此时  订单服务 既是 服务消费者 （相对于 会员服务 、预约服务）又是 服务的提供者 （相对于 H5 移动端的请求）
    @Reference
    private OrderSettingService orderSettingService;  //  oderSettingMapper

    @Reference
    private MemberService memberService;


    @Override
    @LcnTransaction  //  所有参与者  方法上即可
    public Order add(Map map) {
        //  1. 判断验证码是否正确 或 过期
        String codeFromMap = (String) map.get("validateCode");
        String telephone = (String) map.get("telephone");
        String redisCode = RedisUtil.get(RedisMessageConstant.SENDTYPE_ORDER + telephone);
         if(StringUtils.isBlank(redisCode)){
             //  过期
             throw  new RuntimeException("验证码过期");
         }
        if(StringUtils.isBlank(codeFromMap)){
            //  表单验证码null
            throw  new RuntimeException("验证码必须填写");
        }
         if(!redisCode.equals(codeFromMap)){
             //  验证码错误
             throw  new RuntimeException("验证码错误");
         }
        String orderdate = (String) map.get("orderDate");  //  mysql  select  count(1)  where  number > resxxx and order = ''2020-11-1
        String lockkey = "setmeal:lock:" + orderdate;  //  按照日期 预约套餐  分布式锁  按照抢占的资源  定义key   类似 队列  排队抢占资源
        try {
            if (RedisUtil.lock(lockkey)) {  //  每一个预约用户 都要排队 获取一把锁  等预约完之后  释放锁
        //  2  判断是否预约满   t_ordersetting
                Thread.sleep(10); //  防止 数据库提交时，锁未释放 导致数据差异  小睡10毫秒
                int count = orderSettingService.isOrderOk(orderdate);
                System.out.println("---------" + count);
                if (count <= 0) {
                    throw new RuntimeException("预约已满，请选择其他日期");
                }
                //  3  判断当前用户 是否 重复预约   用户  老用户   t_member    手机号查询
                Member memeber = memberService.findMemeberByTelephone(telephone);
                //  select  xxx  from   where  telepphone = ?
                String sid = (String) map.get("setmealId");
                int mid;  //  会员 id
                if (memeber != null) {
                    //  老用户   进一步判断 套餐  当天 是否重复预约   t_order  三个字段判断
                    int orderExist = baseMapper.findOrderBySetmealIdAndOrderDateAndMemberId(Integer.parseInt(sid), orderdate, memeber.getId());
                    mid = memeber.getId();
                    if (orderExist > 0) {
                        throw new RuntimeException("已经预约过，请择日再约");
                    }
                } else {
                    //  更新会员表
                    memeber = new Member();
                    memeber.setName((String) map.get("name"));
                    memeber.setSex((String) map.get("sex"));
                    memeber.setIdCard((String) map.get("idCard"));
                    memeber.setPhoneNumber(telephone);
                    memeber.setRegTime(new Date(System.currentTimeMillis()));
                    mid = memberService.saveMember(memeber);
                }
                //  4:  可以预约  多表更新    t_order  t_ordersetting  t_member
                orderSettingService.updateReservationByOrderDate(orderdate);  //   update  t_ordersetting  set  xx = xxx+1  where orderdate = ?
                //  订单表的录入
                Order order = new Order();
                order.setMemberId(mid);
                order.setOrderDate(DateUtils.parseString2Date(orderdate, "yyyy-MM-dd"));
                order.setOrderType((String) map.get("orderType"));
                order.setSetmealId(Integer.parseInt(sid));
                order.setOrderStatus("未到诊");
                save(order);
                return order;
            } else {
                throw new RuntimeException("该套餐预约很火爆，排队人数较多，请稍后重试！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            RedisUtil.unlock(lockkey);//  确定 数据库 提交数据  commit之后  才可释放当前的锁  下一个用户才可以获取一把锁
        }
    }
    @Override
    public Map findOrderInfoByOrderId(int id) {
        return baseMapper.findOrderInfoByOrderId(id);
    }
}
